package org.fujene.diskblock;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import org.fujene.memoryblock.MemoryBlock;
import org.fujene.memoryblock.SkipPointerBlock;
import org.fujene.structure.LookupPointer;
import org.fujene.toolbox.ByteConverter;

public class SkipPointerDiskBlock extends DiskBlock{
	public SkipPointerDiskBlock(File fileDesc){
		super(fileDesc);
	}

	public SkipPointerDiskBlock(SkipPointerBlock memBlock, String dir){
		super(memBlock, dir);
	}

	public int getSkipType() throws Exception{
		return getOption(2);
	}

	public int getNextblock() throws Exception{
		return getOption(1);
	}

	public int getLength() throws Exception{
		return getOption(0);
	}

	public LookupPointer getPointer(int index) throws Exception{
		// OutOfBounds
		if(index >= getOption(0))
			return null;
		return ByteConverter.getPtr(getBody(index * PTR, PTR));
	}

	@Override
	public void readToMemory(MemoryBlock memBlock){
		if(memBlock instanceof SkipPointerBlock){
			try{
				memBlock.setOption(0, this.getOption(0));
				memBlock.setOption(1, this.getOption(1));
				memBlock.setOption(2, this.getOption(2));
				memBlock.setBody(this.getBody(0, this.bodySize), 0);
				memBlock.setBodyVacancy(this.bodyVacancy);
			}catch (Exception e){}
		}
	}

	@Override
	public byte[] getData(){
		ByteArrayOutputStream stream = new ByteArrayOutputStream(this.bodySize + 4);

		try{
			stream.write(ByteConverter.intToByte(this.getOption(0), 4));
			stream.write(ByteConverter.intToByte(this.getOption(1), 4));
			stream.write(ByteConverter.intToByte(this.getOption(2), 4));
			stream.write(this.getBody(0, this.bodySize));
		}catch (IOException e){}

		return stream.toByteArray();
	}
}
